const { parentPort } = require('worker_threads')
const { workerData } = require('node:worker_threads')
const schedule = require('node-schedule')

// 创建 WebSocket 服务器
const WebSocket = require('ws').WebSocket
// 创建一个 WebSocket 服务器实例，监听在 8080 端口
const wss = new WebSocket.Server({
  port: workerData.port,
  clientTracking: true
})

let job = null

// 存储客户端连接
const clients = new Map()
// WebSocket连接处理
wss.on('connection', (ws, req) => {
  // 消息处理
  ws.on('message', (message) => {
    try {
      const parsedMessage = JSON.parse(message)
      switch (parsedMessage.type) {
        case 'connection':
          console.log('客户端已连接:', parsedMessage)
          clients.set(parsedMessage.data, ws)
          break
        case 'time':
          handleTimeMessage(parsedMessage)
          break
        default:
          console.log('未知消息类型:', parsedMessage.type)
      }
    } catch (error) {
      // console.error('消息解析错误:', error);
    }
  })

  // 连接关闭处理
  ws.on('close', () => {
    // 遍历客户端连接，检查连接状态并移除断开连接的连接
    clients.forEach((client, clientId) => {
      if (client.readyState === client.CLOSED) {
        // 发送离线消息到主线程
        parentPort.postMessage(
          JSON.stringify({
            type: 'userLeft',
            data: clientId
          })
        )
        // 移除客户端
        clients.delete(clientId)
        console.log(`客户端${clientId}已断开连接`)
      }
    })
  })

  // 定义规则
  const rule = new schedule.RecurrenceRule()
  //生成间隔5秒一次
  rule.second = new schedule.Range(0, 59, 5)
  // 启动任务
  if (job === null) {
    job = schedule.scheduleJob(rule, () => {
      parentPort.postMessage(
        JSON.stringify({
          type: 'clients',
          data: Array.from(clients.keys()) //将clients的key转成字符数组
        })
      )
    })
  }
})

// 时间消息处理
function handleTimeMessage(message) {
  const parsedMessage = JSON.stringify(message)
  // console.log('接收到时间消息:', parsedMessage)
  // 发送消息到主线程
  parentPort.postMessage(parsedMessage)
}

// 广播消息
function broadcast(message, excludeClientId = null) {
  clients.forEach((client, clientId) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(message))
    }
  })
}

console.log('服务器 ：WebSocket server is running on ws://localhost:' + workerData.port)
console.log('WebSocket状态:', WebSocket.OPEN)
